﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace Client_Test
{
    class ClientThread
    {
        Thread thread;
        TcpClient client;
        NetworkStream stream;
        public int ID;
        string username;
        bool isListening;
        const int MAPID = 1;
        const int CHATID = 2;
        const int MAPREQUEST = 3;
        const int MAPRECEIVED = 4;

        public ClientThread(ref TcpClient socket)
        {
            ID = 0;
            isListening = false;
            client = socket;
            thread = new Thread(() => Listen());
        }

        public void StartListening()
        {
            if (isListening == false)
            {
                isListening = true;
                stream = client.GetStream();
                thread.Start();
                if (!GameState.IsHost)
                {
                    byte[] bytes = new byte[sizeof(int)];
                    int i = stream.Read(bytes, 0, bytes.Length);
                    ID = (NetworkManager.BytesToInt(bytes))[0];
                }
            }
        }

        private void Listen()
        {
            int i;
            //Byte[] bytes = new Byte[256];
            while (stream.CanRead)
            {
                Byte[] bytes = new Byte[4];
                i = stream.Read(bytes, 0, bytes.Length);
                int[] array = new int[1];
                Buffer.BlockCopy(bytes, 0, array, 0, sizeof(int));
                switch (array[0])
                {
                    case MAPID:
                        NetworkManager.ReadMapMessage(stream);
                        break;

                    case CHATID:
                        NetworkManager.ReadChatMessage(stream);
                        break;

                    case MAPREQUEST:
                        //SendMap(ip);
                        break;

                    default:
                        break;
                }
                //HostThread.MessagesReceived.Enqueue(msg);
                //Console.WriteLine("Forwarding: " + System.Text.Encoding.ASCII.GetString(message, 0, i));
                //HostThread.Forward(message, ID);
            }
        }

        public void Send(Byte[] data)
        {
            //stream.Write(BitConverter.GetBytes(MessageID), 0, sizeof(int));
            //stream.Write(BitConverter.GetBytes(ID), 0, sizeof(int));
            stream.Write(data, 0, data.Length);
        }

        public void Close()
        {
            isListening = false;
            stream.Close();
            client.Close();
            username = null;
        }
    }
}
